package cn.com.infcn.spider.util;

import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.nutz.ioc.Ioc;
import org.nutz.mvc.Mvcs;

import cn.com.infcn.spider.web.BootStrap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class StaticValue {

	private static final Logger LOG = Logger.getLogger(StaticValue.class);

	private static Ioc ioc;

	// 成功
	public static final String OK = JSONObject.toJSONString(new JsonResult(true));

	// 错误
	public static final String ERR = JSONObject.toJSONString(new JsonResult(false));

	// 成功
	public static final JSONObject OK_J = (JSONObject) JSONObject.toJSON(new JsonResult(true));

	// 错误
	public static final JSONObject ERR_J = (JSONObject) JSONObject.toJSON(new JsonResult(false));

	/**
	 * 失败消息
	 * 
	 * @param message
	 * @return
	 */
	public static String errMessage(Exception e) {
		String error = JSON.toJSONString(errMessageJson(e));
		return error;
	}

	/**
	 * 失败消息
	 * 
	 * @param message
	 * @return
	 */
	public static JsonResult errMessageJson(Exception e) {
		JsonResult jsonResult = new JsonResult(false);
		jsonResult.setException(e);
		return jsonResult;
	}

	/**
	 * 失败消息
	 * 
	 * @param message
	 * @return
	 */
	public static String errMessage(String message) {
		return JSON.toJSONString(errMessageJson(message));
	}

	public static JsonResult errMessageJson(String message) {
		JsonResult jsonResult = new JsonResult(false);
		jsonResult.setMessage(message);
		return jsonResult;
	}

	/**
	 * 成功消息
	 * 
	 * @param message
	 * @return
	 */
	public static String okMessage(String message) {
		return JSON.toJSONString(okMessageJson(message));
	}

	/**
	 * 成功消息
	 * 
	 * @param message
	 * @return
	 */
	public static JsonResult okMessageJson(String message) {
		JsonResult jsonResult = new JsonResult(true);
		jsonResult.setMessage(message);
		return jsonResult;
	}

	public static Ioc getIoc() {
		if (ioc != null) {
			return ioc;
		}
		ioc = Mvcs.getIoc();

		return ioc;
	}

	/**
	 * 從ｉｏｃ容器中獲取ｂｅａｎ
	 * 
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		return getIoc().get(null, name);
	}

	/**
	 * 從ｉｏｃ容器中獲取ｂｅａｎ
	 * 
	 * @param name
	 * @return
	 */
	public static <T> T getBean(Class<T> t, String name) {
		return getIoc().get(t, name);
	}

	public static void setIoc(Ioc ioc) {
		StaticValue.ioc = ioc;
	}

	/**
	 * 从配置文件查找
	 * 
	 * @param key
	 * @return
	 */
	public static String getResource(String key) {
		ResourceBundle bundle = ResourceBundle.getBundle("config");
		if (bundle.containsKey(key)) {
			return bundle.getString(key);
		} else {
			return null;
		}
	}

	/**
	 * 加载IOC
	 */
	public static void initIOC() {
		NutzUtil.init(BootStrap.class);
	}

}
